try:
    import xml.etree.cElementTree as ET
except ImportError:
    import  xml.etree.ElementTree as ET

import random
import optparse
import io


def generate_departure(n, mu, sigma):
    sample = [int(random.gauss(mu, sigma)) for i in range(n)]
    return sample

def modify_depart(trips, time_dist):
    assert isinstance(trips, list)
    assert isinstance(time_dist, list)
    assert len(trips) == len(time_dist)
    time_dist.sort()

    for i, trip in enumerate(trips):
        assert isinstance(trip, dict)
        if 'depart' not in trip:
            trips[i].setdefault('depart', None)
        trips[i]['depart'] = time_dist[i]
    return trips


def get_options(args=None):
    parser = optparse.OptionParser()
    parser.add_option("-r", "--route", dest="route", help="route file")
    parser.add_option("-m", "--mu", dest="mu", type='float',help="the mean of departure time")
    parser.add_option("-s", "--std", dest="std", type='float',help="the standard error deviation of departure time")
    parser.add_option("-o", "--output", dest="output", help="the output route file")
    (options, args) = parser.parse_args(args=args)
    if not options.route or not options.mu or not options.std or not options.output:
        parser.print_help()
        exit(1)
    return options


def main(options=None):
    print options.route
    trips = io.load_routes(options.route)
    time_dist = generate_departure(len(trips), options.mu, options.std)
    trips = modify_depart(trips, time_dist)
    io.write_routes_text(options.output, trips)


if __name__ == '__main__':
    main(get_options())